# encoding:utf-8
import jwt
import pymysql
from flask import Flask, request, render_template, make_response, jsonify

app = Flask(__name__)

JWT_SALT = '1'

# #############################################################################################
# 1. 配置mysql
# #############################################################################################
def sql():
    conn = pymysql.connect(host='user-db', user="root", passwd="123456", database="userdb")
    cursor = conn.cursor()
    
    return conn, cursor
    
conn, cursor = sql()
###############################################################################################

@app.route("/", methods=['GET', 'POST'])
@app.route('/Page_register.html', methods=['GET', 'POST'])
def hello():
    if request.method == "GET":
        return render_template("/address.html")

@app.route('/tiandizhi', methods=['GET', 'POST'])
def tiandizhi():
    if request.method == "POST":
        # - - - - 获取前端信息 - - - - -
        infoFromWeb = request.json
        token = infoFromWeb["token"]
        name = infoFromWeb["name"]
        print(name)
        telNum = infoFromWeb["telNum"]
        a_sheng = infoFromWeb["a_sheng"]
        a_shi = infoFromWeb["a_shi"]
        detail = infoFromWeb["detail"]
        
        print(detail)
        if '' in [token, name, telNum, a_sheng, a_shi, detail]:
            return make_response(jsonify({'stateCode': -3}), 200)  # stateCode(-3): 表示内容空缺
        
        print("数据正常:", [token, name, telNum, a_sheng, a_shi, detail])
        try:
            # - - - - 解析前端信息 - - - - -
            payload = jwt.decode(token, JWT_SALT, algorithms='HS256')
            
            if not payload:
                return make_response(jsonify({'stateCode': -1}), 200)  # stateCode(-1): 表示登录状态过期
                
            user_id = payload['UserID']
            print(user_id)

            # - - - - 查询是否已经填过地址 - - - - -
            sql_is_add = "SELECT is_address FROM userTable WHERE UserId = %d" % user_id
            cursor.execute(sql_is_add)
            is_add = cursor.fetchone()  # is_add: (1,)

            try:
                is_add = int(is_add[0])  # 如果数据库中有该用户
                
                if is_add == 0:  # 如果没填写地址
                
                    try:
                        # - - - - 插入数据库 - - - - -
                        sql_insert_adTable = "INSERT INTO addressTable (UserId, mobile, sheng, shi, detail, name) values (%d, \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')" % (user_id, telNum, a_sheng, a_shi, detail, name)
                        print("sql_insert_adTable:", sql_insert_adTable)
                        cursor.execute(sql_insert_adTable)
                        conn.commit()
                    except:
                        return make_response(jsonify({'stateCode': -2}), 200)  # stateCode(-2): 表示插入数据库错误
                        
                elif is_add == 1:  # 如果填写了地址
                
                    try:
                        # - - - - 更新数据库 - - - - -
                        sql_update_adTable = "UPDATE addressTable SET mobile=\'%s\', sheng=\'%s\', shi=\'%s\', detail=\'%s\', name=\'%s\' WHERE UserId=%d" % (telNum, a_sheng, a_shi, detail, name, user_id)
                        print(sql_update_adTable)
                        cursor.execute(sql_update_adTable)
                        conn.commit()
                    except:
                        return make_response(jsonify({'stateCode': -2}), 200)  # stateCode(-2): 表示插入数据库错误
                        
                else:  # 未知错误
                    return make_response(jsonify({'stateCode': -100}), 200)  # stateCode(-100): 表示未知错误
                    
            except:  # 如果数据库中没有该用户
                sql_insert_user = "INSERT INTO userTable (UserId, is_suc, is_address) VALUES (%d, %d, %d)" % (user_id, 0, 0)
                cursor.execute(sql_insert_user)
                conn.commit()
                
                # - - - - 插入数据库 - - - - -
                sql_insert_adTable = "INSERT INTO addressTable (UserId, mobile, sheng, shi, detail, name) values (%d, %s, %s, %s, %s, %s)" % (user_id, telNum, a_sheng, a_shi, detail, name)
                cursor.execute(sql_insert_adTable)
                conn.commit()
            
            sql_update_is_add = "UPDATE userTable SET is_address = 1 WHERE UserId = %d " % user_id
            cursor.execute(sql_update_is_add)
            conn.commit()
            
            return make_response(jsonify({'stateCode': 1}), 200)  # stateCode(1): 表示插入成功
        
        except:
            return make_response(jsonify({'stateCode': -100}), 200)  # stateCode(-100): 表示未知错误
        


app.run(host='0.0.0.0', port=3354)
